package cn.tedu.clyback.user.service.impl;


import cn.tedu.clyback.base.exception.ServiceException;
import cn.tedu.clyback.base.response.StatusCode;
import cn.tedu.clyback.user.mapper.UserMapper;
import cn.tedu.clyback.user.pojo.dto.UserLoginParam;
import cn.tedu.clyback.user.pojo.dto.UserQuery;
import cn.tedu.clyback.user.pojo.dto.UserSaveParam;
import cn.tedu.clyback.user.pojo.entity.User;
import cn.tedu.clyback.user.pojo.vo.PermissionVO;
import cn.tedu.clyback.user.pojo.vo.UserVO;
import cn.tedu.clyback.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("用户登录，参数：{}", userLoginParam);
        UserVO userVO = userMapper.selectByUsername(userLoginParam.getUsername());
        if (userVO == null) {
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginParam.getPassword())) {
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return userVO;
    }

    @Override
    public void saveUser(UserSaveParam userSaveParam) {
        User user = new User();
        BeanUtils.copyProperties(userSaveParam, user);
        if (user.getUserId() == null) {
            //新增用户时要判断该用户名是否存在
            if (userMapper.selectByUsername(user.getUsername()) != null) {
                throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
            }
            //注意:员工数据不是员工自己注册的，所以需要预设一个初始密码
            user.setPassword("123456");
            user.setCreateTime(new Date());
            userMapper.insert(user);
        } else {
            user.setUpdateTime(new Date());
            userMapper.update(user);
        }
    }
    //查询用户列表
    @Override
    public List<UserVO> selectUser(UserQuery userQuery) {
        List<UserVO> list = userMapper.selectUser(userQuery);
        return list;
    }
    @Override
    public void resetPassword(Long userId) {
        User user = new User();
        user.setUserId(userId);
        user.setPassword("admin");
        userMapper.update(user);
    }
    @Override
    public void updateStatus(Long userId, String status) {
        User user = new User();
        user.setUserId(userId);
        user.setStatus(status);
        userMapper.update(user);
    }

    @Override
    public void deleteUser(Long userId) {
        userMapper.deleteById(userId);
    }

    @Override
    public HashSet<PermissionVO>  getPermissions(Integer userId) {
        HashSet<PermissionVO> set= userMapper.getPermissions(userId);
        return set;
    }
}